﻿using System;
using System.Collections;
using System.Web.UI;

namespace RoketSolutions.SP2010.SecurityTrimming.Helpers
{
    public class ControlEnumerator
    {
        private Control RootControl
        {
            get;
            set;
        }

        public ControlEnumerator(Control root)
        {
            RootControl = root;
        }

        public void Enumerate<TSource>(Action<TSource> doAction) where TSource : Control
        {
            if (null == RootControl)
                return;

            if (RootControl is TSource)
                doAction((TSource)RootControl);

            if (RootControl.Controls.Count > 0)
                Enumerate(RootControl.Controls, doAction);
        }

        private void Enumerate<TSource>(IEnumerable controlCollection, Action<TSource> doAction) where TSource : Control
        {
            foreach (Control control in controlCollection)
            {
                if (control is TSource)
                    doAction((TSource)control);

                var childControls = control.Controls;
                if (childControls.Count > 0)
                    Enumerate(childControls, doAction);
            }
        }
    }
}